package com.tool.cn.freemaker;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tool.cn.freemaker.model.ModelInformation;


/**
 * 读取txt配置生成实体类
 * @author wangzh
 * @date 2020年3月6日 下午3:26:17
 */
public class ModelTemplate {


	
	private final Logger log= LoggerFactory.getLogger(this.getClass());
	
	public static void main(String[] args) {
		String file="D:\\Mars-workspace\\think_object\\src\\main\\resources\\model.txt";
		ModelTemplate core=new ModelTemplate();
		List<ModelInformation> modelList=core.analysis(file);
		core.createClass(modelList);
	}
	
	/**
	 * 解析txt文件
	 * @param file
	 * @return 
	 */
	public List<ModelInformation> analysis(String file){
		BufferedReader buf = null;
		List <ModelInformation> modelList=new ArrayList<>();
		try {
			 buf=new BufferedReader(new InputStreamReader(new FileInputStream(file)));
			String context;
			ModelInformation model;
			String[] data,detail;
			Map<String,String> column;
			while((context=buf.readLine())!=null){
				if(context.startsWith("#")){
					continue;
				}
				model=new ModelInformation();
				column=new LinkedHashMap<>();
				
				//#目录|类名|作者|注释|字段名=类型,字段名=类型...
				data=context.split("\\|");
				model.setPath(data[0]);
				model.setClassName(data[1]);
				model.setAuther(data[2]);
				model.setNotes(data[3]);
				data=data[4].split("\\,");
				for(String one:data){
					detail=one.split("\\=");
					column.put(detail[0], detail[1]);
				}
				model.setModel(column);
				modelList.add(model);
			}
			
			
		}catch(Exception e){
			log.error(e.toString(), e);
		}finally{
			try {
				if(buf!=null){
					buf.close();
				}
			} catch (IOException e) {
				log.error(e.toString(),e);
			}
		}
		return modelList;
	}
	
	
	/**
	 * 创建模型类
	 * @param modelList
	 */
	public void createClass(List<ModelInformation> modelList){
		File path;
		String packageName;
		int index;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置格式化格式
		String nowDate = sdf.format(new Date());
		
		try {
			for(ModelInformation model:modelList){
				//目录
				path=new File(model.getPath());
				if(!path.exists()){
					path.mkdirs();
				}
				
				
				index=model.getPath().indexOf("src");
				packageName=model.getPath().substring(index).replace("src\\\\main\\\\java\\\\", "").replace("\\\\", ".")+";";
				//生成类:注释|类型=字段名,类型=字段名.
				
				BufferedWriter write=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path+File.separator+model.getClassName()+".java")));
				StringBuffer sb = new StringBuffer();
				//包名
				sb.append("package ").append(packageName).append("\r\n");
				
				// 注释部分
				sb.append("/**\r\n");
				sb.append(" * " + model.getNotes() + "\r\n");
				sb.append(" * @author "+model.getAuther()+" \r\n");
				sb.append(" * @date " + nowDate + "\r\n");
				sb.append(" */ \r\n");
				
				//类
				sb.append("public class  ").append(initcap(model.getClassName())).append("{\r\n");
				processAllAttrs(sb,model.getModel());  //属性
				processAllMethod(sb,model.getModel());  //方法
				
				sb.append("}");
				write.write(sb.toString());
				write.flush();
				write.close();
				
			}
		} catch (Exception e) {
			log.error(e.toString(),e);
		}
		
	}
	
	/**
	 * 功能：将输入字符串的首字母改成大写
	 * 
	 * @param str
	 * @return
	 */
	private String initcap(String str) {

		char[] ch = str.toCharArray();
		if (ch[0] >= 'a' && ch[0] <= 'z') {
			ch[0] = (char) (ch[0] - 32);
		}
		return new String(ch);
	}
	
	/**
	 * 功能：生成所有属性
	 * 
	 * @param sb
	 */
	private void processAllAttrs(StringBuffer sb,Map<String,String> column) {
		
		for(String key:column.keySet()){
			sb.append("\tprivate " + column.get(key) + " " + key + ";\r\n");
		}
		
		sb.append("\n");
	}

	/**
	 * 功能：生成所有方法
	 * 
	 * @param sb
	 */
	private void processAllMethod(StringBuffer sb,Map<String,String> column) {

		for(String key:column.keySet()){
			sb.append("\tpublic void set" + initcap(key) + "("
					+ column.get(key) + " " + key
					+ "){\r\n");
			sb.append("\t\tthis." + key + "=" + key + ";\r\n");
			sb.append("\t}\r\n\n");
			sb.append("\tpublic " + column.get(key) + " get"
					+ key + "(){\r\n");
			sb.append("\t\treturn " + key + ";\r\n");
			sb.append("\t}\r\n\n");
		}

	}

}
